package com.zhiyou.aifeng.smart_machine

import android.annotation.SuppressLint
import android.app.Activity
import android.content.pm.ActivityInfo
import android.content.res.TypedArray
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.Gravity
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.alibaba.android.arouter.launcher.ARouter
import com.github.zackratos.ultimatebar.ultimateBarBuilder
import com.lzy.okgo.utils.OkLogger
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import com.zhiyou.aifeng.common.base.getColorEx
import com.zhiyou.aifeng.common.base.invisible
import com.zhiyou.aifeng.common.helper.*
import com.zhiyou.aifeng.common_ui.base.BaseDialog
import com.zhiyou.aifeng.common_ui.router.Routers
import com.zhiyou.aifeng.common_ui.utils.showHintDialog
import com.zhiyou.aifeng.utils.registerOnPageChanged
import com.zhiyou.aifeng.view.ImageGuideAdapter
import com.zhiyou.aifeng.view.bannerViewPager
import com.zhpan.bannerview.BannerViewPager
import com.zhpan.bannerview.BaseViewHolder
import com.zhpan.indicator.enums.IndicatorSlideMode
import com.zhpan.indicator.enums.IndicatorStyle
import org.jetbrains.anko.*
import org.jetbrains.anko.sdk25.listeners.onClick
import java.lang.reflect.Field
import java.lang.reflect.Method


/**
 * 不继承BaseActivity，解决打开显示空白的问题
 */
class GuideActivity : AppCompatActivity() {

    private lateinit var mViewPager: BannerViewPager<Int, BaseViewHolder<Int>>
    private lateinit var tvSkip: TextView
    private var isReady: Boolean = false
    private var mDialog: BaseDialog? = null

    @SuppressLint("HandlerLeak")
    private var handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (isReady) startGuide()
            else isReady = true
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        // 解决android 8.0时screenOrientation垂直时崩溃的问题
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O
            && isTranslucentOrFloating()
        ) fixOrientation()
        super.onCreate(savedInstanceState)

        ultimateBarBuilder().apply {
            statusDark(false)
            statusDrawable(ColorDrawable(Color.TRANSPARENT))
            applyNavigation(false)
        }
            .create()
            .immersionBar()

        OkLogger.e("${getScreenWidth()}, ${getScreenHeight()}")

        frameLayout {
            imageView {
                imageResource = R.mipmap.icon_guide
                scaleType = ImageView.ScaleType.FIT_XY
            }.lparams(
                width = matchParent,
                height = matchParent
            )

            mViewPager = bannerViewPager<Int> {
                setAutoPlay(false)
                adapter = ImageGuideAdapter()
                setIndicatorStyle(IndicatorStyle.ROUND_RECT)
                setIndicatorSlideMode(IndicatorSlideMode.SCALE)
                setIndicatorSliderGap(dp2px(6f))
                setIndicatorHeight(dp2px(6f))
                setIndicatorMargin(0, 0, 0, dp2px(20f))
                setIndicatorSliderWidth(dp2px(6f), dp2px(12f))
                setIndicatorSliderColor(
                    getColorEx(R.color.lighter),
                    getColorEx(R.color.colorAccent)
                )
                registerOnPageChanged {
                    onPageSelected {

                    }
                }
                setOnPageClickListener { if (it == 2) quitGuide() }
                create()
            }.lparams(
                width = matchParent,
                height = matchParent
            )

            tvSkip = themedTextView("跳过", R.style.Font15_white) {
                gravity = Gravity.CENTER
                backgroundResource = R.drawable.rec_bg_ova_66000000
                horizontalPadding = dip(25)
                verticalPadding = dip(6)
                invisible()

                onClick { quitGuide() }
            }.lparams {
                gravity = Gravity.END
                topMargin = dip(35)
                rightMargin = dip(20)
            }
        }

        ActivityStack.screenManager.pushActivity(this)

        window.decorView.postDelayed(
            { handler.sendEmptyMessage(0) },
            2000
        )

        requestPermission()
    }

    override fun onRestart() {
        super.onRestart()
        mDialog?.let { if (!it.isShowing) requestPermission() }
    }

    private fun requestPermission() {
        AndPermission.with(this)
            .runtime()
            .permission(
                Permission.ACCESS_COARSE_LOCATION,
                Permission.ACCESS_FINE_LOCATION,
                Permission.READ_EXTERNAL_STORAGE,
                Permission.WRITE_EXTERNAL_STORAGE,
                Permission.CAMERA
            )
            .onGranted { handler.sendEmptyMessage(0) }
            .onDenied {
                val hintList = ArrayList<String>()
                if (Permission.ACCESS_COARSE_LOCATION in it) hintList.add("获取设备位置信息请求失败")
                if (Permission.READ_EXTERNAL_STORAGE in it) hintList.add("获取存储信息访问请求失败")
                if (Permission.CAMERA in it) hintList.add("获取系统相机拍照请求失败")

                showPermissionDialog(hintList.joinToString("，\n"))
            }
            .start()
    }

    private fun showPermissionDialog(hint: String) {
        if (mDialog?.isShowing == true) return

        mDialog = showHintDialog(
            title = "提示",
            hint = hint,
            sure = "去设置",
            cancel = "退出",
            isForced = true,
            onCancel = { ActivityStack.screenManager.popActivities(this::class.java) },
            onSure = { PermissionPageHelper(this).jumpPermissionPage() }
        )
    }

    private fun startGuide() {
        if (getString("guideFlag").isEmpty()) {
            val imgs = listOf(
                R.mipmap.guide_img01,
                R.mipmap.guide_img02,
                R.mipmap.guide_img03
            )
            mViewPager.refreshData(imgs)
        } else quitGuide()
    }

    private fun quitGuide() {
        putShared("guideFlag", "normal")
        if (isLogin) startActivity<MainActivity>()
        else {
            ARouter.getInstance()
                .build(Routers.login)
                .navigation()
        }
        ActivityStack.screenManager.popActivities(this::class.java)
    }

    override fun onBackPressed() {}

    @SuppressLint("PrivateApi")
    private fun isTranslucentOrFloating(): Boolean {
        var isTranslucentOrFloating = false
        try {
            val styleableRes =
                Class.forName("com.android.internal.R\$styleable")
                    .getField("Window")[null] as IntArray
            val ta = obtainStyledAttributes(styleableRes)
            val method: Method =
                ActivityInfo::class.java.getMethod(
                    "isTranslucentOrFloating",
                    TypedArray::class.java
                )
            method.isAccessible = true
            isTranslucentOrFloating = method.invoke(null, ta) as Boolean
            method.isAccessible = false
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return isTranslucentOrFloating
    }

    private fun fixOrientation(): Boolean {
        try {
            val field: Field = Activity::class.java.getDeclaredField("mActivityInfo")
            field.isAccessible = true
            (field.get(this) as ActivityInfo).screenOrientation = -1
            field.isAccessible = false
            return true
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return false
    }

    override fun setRequestedOrientation(requestedOrientation: Int) {
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O
            && isTranslucentOrFloating()
        ) return
        super.setRequestedOrientation(requestedOrientation)
    }

}